# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
import json
from zhihuuser.items import UserItem


class UserSpider(scrapy.Spider):
    name = 'user'
    allowed_domains = ['www.zhihu.com']
    start_urls = ['http://www.zhihu.com/']

    url = 'https://www.zhihu.com/api/v4/members/{user}?{include}'
    url_query = 'include=allow_message%2Cis_followed%2Cis_following%2Cis_org%2Cis_blocking%2Cemployments%2Canswer_count%2Cfollower_count%2Carticles_count%2Cgender%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics'
    follow_url = 'https://www.zhihu.com/api/v4/members/{user}/followees?include={include}offset={offset}&limit={limit}'
    follow_query = 'data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics&'

    def start_requests(self):
        yield Request(url=self.url.format(user='excited-vczh', include=self.url_query), callback=self.parse_user)
        yield Request(url=self.follow_url.format(user='excited-vczh',include=self.follow_query,offset=0,limit=20),callback=self.parse_follow)

    def parse_user(self, response):
        results = json.loads(response.text)
        item = UserItem()
        for field in item.fields:
            if field in results.keys():
                item[field] = results.get(field)
        yield item

    def parse_follow(self, response):
        results = json.loads(response.text)

        if 'data' in results.keys():
            for item in results['data']:
                yield Request(url=self.url.format(user=item.get('url_token'),include=self.url_query),callback=self.parse_user)

        if 'paging' in results.keys() and results.get('paging').get('is_end') == 'false':
            next_page = results.get('paging').get('next')
            yield  Request(next_page,callback=self.parse_follow)
